package com.twu.biblioteca;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.util.ArrayList;

public class CustomerAccountManager {
    private ArrayList<Customer> customers = new ArrayList<Customer>();

    public CustomerAccountManager() {
    }

    public CustomerAccountManager(String xmlFilePath) {
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        Document document = null;
        Element rootElement = null;

        try {
            DocumentBuilder builder = builderFactory.newDocumentBuilder();
            document = builder.parse(new File(xmlFilePath));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        rootElement = document.getDocumentElement();
        NodeList customerList = rootElement.getElementsByTagName("Customer");

        if (customerList != null) {
            for (int i = 0; i < customerList.getLength(); i++) {
                Node customerNode = customerList.item(i);
                NodeList infoNodeList = customerNode.getChildNodes();
                String libraryNumber = infoNodeList.item(1).getTextContent();
                String password = infoNodeList.item(3).getTextContent();
                String name = infoNodeList.item(5).getTextContent();
                String email = infoNodeList.item(7).getTextContent();
                String phoneNumber = infoNodeList.item(9).getTextContent();

                add(new Customer(libraryNumber, password, name, email, phoneNumber));
            }
        }
    }

    public int getAccountNumber() {
        return customers.size();
    }

    public void add(Customer customer) {
        customers.add(customer);
    }

    public Customer getCustomer(String libraryNumber, String password) {
        for (int i = 0; i < getAccountNumber(); i++) {
            Customer customer = customers.get(i);
            if (customer.getLibraryNumber().equals(libraryNumber) && customer.getPassword().equals(password))
                return customer;
        }
        return null;
    }
}
